<?php
namespace app\voice\controller;
use think\Db;

/**
 * 前台首页控制器
 * @package app\api\controller
 */
class Index extends Auth
{
    public $noNeedLogin = [];

    public function index()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $userInfo = $this->userInfo;
            $voice_config = Db::name('qt_voice_config')->where('id',1)->find();
            $where['sq.store_id'] = $userInfo['store_id'];
            //性别筛选
            if(isset($getData['sex'])){
                $where['u.sex'] = $getData['sex'];
            }
            //班次筛选
            if(isset($getData['work_type'])){
                $where['u.work_type'] = $getData['work_type'];
            }
            //状态筛选
            if(isset($getData['work_status'])){
                $where['u.work_status'] = $getData['work_status'];
            }
            //技师工号搜索
            if(isset($getData['work_number'])){
                $where['u.work_number'] = $getData['work_number'];
            }
            //待安排
            if(isset($getData['room'])){
                if($getData['room'] == '2'){
                    $where['u.room_id'] = '0';
                }
            }

            //隐藏数据
            if (!empty($voice_config)){

                if ($voice_config['hidden'] == 2) {
                    $where[] = ['u.work_status','<>',7];//工作状态  1 上班 2 未上班 3 有预约 4 服务中 5 未到达  6 圈牌中 7 请假
                }
                if ($voice_config['no_work'] == 2) {
                    $where[] = ['u.work_status','<>',2];//工作状态  1 上班 2 未上班 3 有预约 4 服务中 5 未到达  6 圈牌中 7 请假
                }
            }

            //用户数据
            $userRes = Db::name('qt_scheduling_queue')
                ->field('u.work_number,u.sex,st.title as name,u.id as user_id,u.room_id,sq.sort,u.work_type,u.work_status')
                ->alias('sq')
                ->leftJoin('qt_users u','u.id = sq.engineer_id')
                ->leftJoin('qt_scheduling_type st','st.id = u.work_type')
                ->where($where)
                ->order('sq.sort asc')
                ->paginate()->each(function ($item){
                    $item['clock'] = Db::name('qt_commission_log')
                        ->where(['user_id'=>$item['user_id'],'type'=>'1','status'=>'2'])
                        ->whereTime('created_time','today')
                        ->count();
                    $item['row'] = Db::name('qt_commission_log')
                        ->where(['user_id'=>$item['user_id'],'type'=>'1','status'=>'1'])
                        ->whereTime('created_time','today')
                        ->count();
                    $item['room'] = Db::name('qt_room')
                        ->where(['id'=>$item['room_id']])
                        ->value('name');
                    $product = Db::name('qt_order_project')
                        ->field('op.order_type,p.name')
                        ->alias('op')
                        ->leftJoin('qt_project p','op.project_id = p.id')
                        ->where(['engineer_id'=>$item['user_id']])
                        ->where('op.is_delete',2)
                        ->whereIn('op.status',['1','2'])
                        ->find();
                    $item['product_name'] = $product['name'];
                    $item['product_type'] = $product['order_type'];
                    return $item;
                });
            //总数据
            $this->result('查询成功', $userRes, 200);
        }
    }


    /**
     * 获取房间状态
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getRoomStatus()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $data = Db::name('qt_room_status')
                ->field('id,name,color')
                ->where(['store_id' => $userInfo['store_id'], 'status' => '1'])
                ->order('sort asc')
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 技师播报
     * @throws \think\exception\DbException
     */
    public function engineer(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $getData['limit'] = empty($getData['limit']) ? 10 : $getData['limit'];
            $data = Db::name('qt_order_queue')
                ->field('oq.id,u.work_number,o.name,r.name as room_name,o.order_type,o.created_time')
                ->alias('oq')
                ->leftJoin('qt_users u','u.id = oq.user_id')
                ->leftJoin('qt_room r','r.id = oq.room_id')
                ->leftJoin('qt_order_project o','o.id = oq.order_project_id')
                ->where('oq.status','2')
                ->where('o.is_delete',2)
                ->whereNotNull('o.engineer_id')
                ->order('o.id desc')
                ->paginate($getData['limit']);
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求方式', '', 204);
    }


    /**
     * 技师等待列表
     */
    /**
     * 获取房间等待列表
     */
    public function wait(){
        if($this->request->isPost()){
            $data = Db::name('qt_wait')
                ->field('ro.*,u.real_name create_user_name, u2.real_name as engineer_name,u2.sex,p.name as project_name ,r.name as room_name')
                ->alias('ro')
                ->leftJoin('qt_users u','u.id = ro.create_id')
                ->leftJoin('qt_users u2','u2.id = ro.engineer_id')
                ->leftJoin('qt_room r','r.id = ro.room_id')
                ->leftJoin('dp_qt_project p','p.id = ro.project_id')
                ->where(['ro.store_id'=>$this->userInfo['store_id'],'ro.status'=>'1'])
                ->where('ro.number','>','0')
                ->select();

            foreach ($data as $key => &$item) {
                $order_queue = Db::name('qt_order_queue')->where('user_id',$item['engineer_id'])->value('end_time');
                $item['waiting'] = !empty($order_queue) ? floor(($order_queue - time()) / 60) : '';
                $item['await'] = !empty($item['create_time']) ? floor((time() - $item['create_time']) / 60) : '';
            }
            $this->result('查询成功',$data,200);
        }
        $this->result('无效的请求','',204);
    }


    /**
     * 获取钟房所有用户数据
     */
    public function getEngineerList(){

        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $userInfo = $this->userInfo;
            $where['oq.store_id'] = $userInfo['store_id'];
            //状态筛选
            if(!empty($getData['work_status'])){
                $where['u.work_status'] = $getData['work_status'];
            }
            //技师工号搜索
            if(!empty($getData['work_number'])){
                $where['u.work_number'] = $getData['work_number'];
            }

            $voice_config = Db::name('qt_voice_config')->where('store_id',$this->userInfo['store_id'])->find();
            //隐藏数据
            if (!empty($voice_config)){
                if ($voice_config['hidden'] == 2) {
                    $where['u.work_status'] = ['<>',7];//工作状态  1 上班 2 未上班 3 有预约 4 服务中 5 未到达  6 圈牌中 7 请假
                }
                if ($voice_config['no_work'] == 2) {
                    $where['u.work_status'] = ['<>',2];//工作状态  1 上班 2 未上班 3 有预约 4 服务中 5 未到达  6 圈牌中 7 请假
                }
            }
            $work_type_data = Db::name('qt_work_type')
                ->field('id,pid,title')
                ->where('store_id',$this->userInfo['store_id'])
                ->order('id desc')->select();
            $work_type_data = $this->treeNode($work_type_data);

            //用户数据
            $userRes = Db::name('qt_order_queue')
                ->field('u.id as user_id,u.work_number,u.sex,wt.title as name,oq.room_id,oq.sort,u.work_type,u.work_status,u.top_type_id,
                st.title as work_title,oq.head,oq.foot,oq.start_time')
                ->alias('oq')
                ->leftJoin('qt_users u','u.id = oq.user_id')
                ->leftJoin('qt_work_type wt','wt.id = u.top_type_id')
                ->leftJoin('qt_scheduling_type st','st.id = u.work_type')
                ->where($where)
                //->where('u.top_type_id','IN',$work_type_id_str)
                ->order('oq.sort asc')
                ->select();

            $result = [];
            foreach ($userRes as $k => $v) {
                foreach ($work_type_data as $type_k=>$type_v){
                    if ($v['top_type_id'] == $type_v['id']) {
                        $result[$type_v['title']][$type_v['title']][] = $this->mergeData($v);
                    }else {
                        if (empty($type_v['childer'])) {
                            continue;
                        }
                        foreach ($type_v['childer'] as $tk => $t_v) {
                            if ($v['top_type_id'] == $t_v['id']) {
                                $result[$type_v['title']][$t_v['title']][] = $this->mergeData($v);
                            }
                        }
                    }
                }
            }
            $this->result('查询成功', $result, 200);

        }
    }

    /**
     * 整理排序所有分类
     * @param  array   $data       从数据库获取的分类
     * @param  integer $parentId 父id,默认一级分类
     * @return array
     */
    private function treeNode($data,$parentId = 0)
    {
        // 用于保存整理好的分类节点
        $node = [];
        // 循环所有分类
        foreach ($data as $key => $value) {
            // 如果当前分类的父id等于要寻找的父id则写入$node数组,并寻找当前分类id下的所有子分类
            if($parentId == $value ['pid']) {
                $node [$key] = $value;
                $node [$key] ['childer'] = $this->treeNode($data,$value ['id']);
            }
        }
        return $node;
    }


    /**
     * 合并数据
     *
     * @param $value
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function mergeData (&$value) {

        $value['clock'] = Db::name('qt_commission_log')
            ->where(['user_id'=>$value['user_id'],'type'=>'1','status'=>'2'])
            ->whereTime('created_time','today')
            ->count();
        $value['row'] = Db::name('qt_commission_log')
            ->where(['user_id'=>$value['user_id'],'type'=>'1','status'=>'1'])
            ->whereTime('created_time','today')
            ->count();
        $room = Db::name('qt_room')
            ->field('r.*,s.name as type_name,s.color as room_color')
            ->alias('r')
            ->leftJoin('qt_room_status s ','s.id = r.status_id')
            ->where(['r.id'=>$value['room_id']])
            ->find();
        $project = Db::name('qt_order_project')
            ->field('op.*,p.id as project,p.name as project_name,p.time')
            ->alias('op')
            ->leftJoin('qt_project p','op.project_id = p.id')
            ->where(['op.room_id'=>$value['room_id'],'op.engineer_id'=>$value['user_id']])
            ->where('op.is_delete',2)
            ->order('id desc')
            ->find();
        $value['room'] = $room['name'];
        $value['color'] = '';
        $value['room_color'] = Db::name('qt_work_status_color')->where('id',$value['work_status'])->value('color');
        if($value['work_status'] == '6'){
            $value['room_color'] = 'rgb(148,173,50)';
        }
        if($value['work_status'] == '7'){
            $value['room_color'] = 'rgb(254,152,0)';
        }
        $value['project_id'] = $project['id'];
        $value['time'] = $project['time'];
        $value['project_type'] = $project['order_type'];
        $value['project_status'] = $project['status'];
        $value['project'] = $project['project'];//项目ID
        $value['project_name'] = $project['project_name'];//项目名称
        //等位
        $wait =  Db::name('qt_wait')->where(['room_id'=>$value['room_id'],'status'=>'1'])->count();
        $value['wait'] = $wait;
        //$value['key'] = $key;//键值对
        //技师是否有预约
        $appointment = Db::name('qt_room_appointment')->where(['engineer_id'=>$value['user_id'],'status'=>'1'])->find();
        if(empty($appointment)){
            $value['appointment'] = 0;//没有预约
        }else{
            $value['appointment'] = 1;//有预约
            if($value['work_status'] == '1'){
                $value['room_color'] = Db::name('qt_work_status_color')->where('id','3')->value('color');
            }
        }

        return $value;
    }

}
